<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>好物快应用、H5端开发小结 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="JavaScript,快应用,">
  

  <meta name="description" content="一、deepLink跳转1.1 快应用中呼起deepLink第一步：检测是安装了app  前提条件：需要知道app的包名  // 判断用户是否安装了appexport const checkInstalledApp = (pkg_name) =&amp;gt; &amp;#123;  const pkg = require(&apos;@system.package&apos;)  return new Promise((resol">
<meta name="keywords" content="JavaScript,快应用">
<meta property="og:type" content="article">
<meta property="og:title" content="好物快应用、H5端开发小结">
<meta property="og:url" content="http://blog.poetries.top/2018/10/19/goods-app-summary/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="一、deepLink跳转1.1 快应用中呼起deepLink第一步：检测是安装了app  前提条件：需要知道app的包名  // 判断用户是否安装了appexport const checkInstalledApp = (pkg_name) =&amp;gt; &amp;#123;  const pkg = require(&apos;@system.package&apos;)  return new Promise((resol">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/1480597-34867938a0263a19.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/1480597-497efe18e83ceac7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3230869-797b8806204eafdf.png">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3230869-a5760a54cfca635d.gif">
<meta property="og:updated_time" content="2020-08-15T04:25:31.910Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="好物快应用、H5端开发小结">
<meta name="twitter:description" content="一、deepLink跳转1.1 快应用中呼起deepLink第一步：检测是安装了app  前提条件：需要知道app的包名  // 判断用户是否安装了appexport const checkInstalledApp = (pkg_name) =&amp;gt; &amp;#123;  const pkg = require(&apos;@system.package&apos;)  return new Promise((resol">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/1480597-34867938a0263a19.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#一、deepLink跳转"><span class="toc-text">一、deepLink跳转</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-1-快应用中呼起deepLink"><span class="toc-text">1.1 快应用中呼起deepLink</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-2-H5页面呼起快应用"><span class="toc-text">1.2 H5页面呼起快应用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#1-3-H5页面呼起deepLink"><span class="toc-text">1.3 H5页面呼起deepLink</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#二、剪贴板分享"><span class="toc-text">二、剪贴板分享</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#三、加载更多"><span class="toc-text">三、加载更多</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#四、搜索历史"><span class="toc-text">四、搜索历史</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#五、骨架屏的应用"><span class="toc-text">五、骨架屏的应用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#六、游客点赞"><span class="toc-text">六、游客点赞</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#七、nodejs递归文件夹上传到阿里云"><span class="toc-text">七、nodejs递归文件夹上传到阿里云</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#八、nodejs实现复制目录到指定文件夹"><span class="toc-text">八、nodejs实现复制目录到指定文件夹</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#九、优化"><span class="toc-text">九、优化</span></a></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-goods-app-summary" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">好物快应用、H5端开发小结</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2018.10.19</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 3.9k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 20分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h2 id="一、deepLink跳转"><a href="#一、deepLink跳转" class="headerlink" title="一、deepLink跳转"></a>一、deepLink跳转</h2><h3 id="1-1-快应用中呼起deepLink"><a href="#1-1-快应用中呼起deepLink" class="headerlink" title="1.1 快应用中呼起deepLink"></a>1.1 快应用中呼起deepLink</h3><p><strong>第一步：检测是安装了app</strong></p>
<blockquote>
<p>前提条件：需要知道app的包名</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 判断用户是否安装了app</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> checkInstalledApp = <span class="function">(<span class="params">pkg_name</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> pkg = <span class="built_in">require</span>(<span class="string">'@system.package'</span>)</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>)=&gt;</span>&#123;</span><br><span class="line">    pkg.hasInstalled(&#123;</span><br><span class="line">      package: pkg_name,</span><br><span class="line">      success: <span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span><br><span class="line">        resolve(data.result) <span class="comment">//返回true、false</span></span><br><span class="line">      &#125;,</span><br><span class="line">      fail: <span class="function"><span class="keyword">function</span> (<span class="params">data, code</span>) </span>&#123;</span><br><span class="line">        reject(code)</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>第二步：调起deepLink</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">let</span> pkg = <span class="string">'com.newsqq.fda'</span> <span class="comment">// 传入包名</span></span><br><span class="line"><span class="keyword">let</span> deep_link = <span class="string">''</span> <span class="comment">// 跳转到app的地址</span></span><br><span class="line"><span class="keyword">let</span> params = &#123;&#125;</span><br><span class="line"></span><br><span class="line">checkInstalledApp(pkg).then(<span class="function"><span class="params">hasInstalledApp</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="comment">// 用户已经安装了app, deep_link直接跳转</span></span><br><span class="line">    <span class="keyword">if</span>(hasInstalledApp &amp;&amp; deep_link)&#123;</span><br><span class="line">      params = &#123;<span class="attr">uri</span>:deep_link&#125;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123; <span class="comment">// 否则跳转到H5地址</span></span><br><span class="line">      params = &#123;</span><br><span class="line">        uri:<span class="string">'Webview'</span>,<span class="comment">//对应于manifest中的配置</span></span><br><span class="line">        params:&#123;</span><br><span class="line">          url,</span><br><span class="line">          title:goods_name</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.$app.$def.router.push(params)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h3 id="1-2-H5页面呼起快应用"><a href="#1-2-H5页面呼起快应用" class="headerlink" title="1.2 H5页面呼起快应用"></a>1.2 <code>H5</code>页面呼起快应用</h3><blockquote>
<p>引入快应用<a href="https://doc.quickapp.cn/tutorial/platform/url-jump-configuration.html" target="_blank" rel="noopener">官方提供的代码</a>,这里做了一下处理</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> quickapp = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  !<span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line"><span class="meta">        "use strict"</span>;</span><br><span class="line">        <span class="built_in">window</span>.appRouter = <span class="function"><span class="keyword">function</span>(<span class="params">e, t, a, o</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> a = a || &#123;&#125;,</span><br><span class="line">            o &amp;&amp; (a.__PROMPT__ = <span class="number">1</span>, a.__NAME__ = o),</span><br><span class="line">            n(e, t, a)</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="built_in">window</span>.installShortcut = <span class="function"><span class="keyword">function</span>(<span class="params">e, t</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> n(<span class="string">"command"</span>, <span class="string">""</span>, &#123;</span><br><span class="line">                type: <span class="string">"shortcut"</span>,</span><br><span class="line">                package: e,</span><br><span class="line">                name: t</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="built_in">window</span>.channelReady = <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> n = &#123;</span><br><span class="line">                available: <span class="keyword">new</span> <span class="built_in">Function</span>,</span><br><span class="line">                availableTimeout: <span class="number">2e3</span></span><br><span class="line">            &#125;;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">"function"</span> == <span class="keyword">typeof</span> e ? n.available = e: <span class="string">"object"</span> == <span class="keyword">typeof</span> e &amp;&amp;</span><br><span class="line">            <span class="function"><span class="keyword">function</span>(<span class="params">e, n</span>) </span>&#123;</span><br><span class="line">                n = n || &#123;&#125;;</span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">var</span> t <span class="keyword">in</span> n) e[t] = n[t]</span><br><span class="line">            &#125; (n, e),</span><br><span class="line">            <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">                <span class="keyword">var</span> n = <span class="string">"http://thefatherofsalmon.com/images"</span>,</span><br><span class="line">                t = <span class="built_in">document</span>.createElement(<span class="string">"img"</span>);</span><br><span class="line">                <span class="keyword">if</span> (t.style.width = <span class="string">"1px"</span>, t.style.height = <span class="string">"1px"</span>, t.style.display = <span class="string">"none"</span>, n += <span class="string">"/"</span> + <span class="number">1e20</span> * <span class="built_in">Math</span>.random(), t.src = n, <span class="built_in">document</span>.body.appendChild(t), t.complete) e.available.call(<span class="literal">null</span>, !<span class="number">0</span>);</span><br><span class="line">                <span class="keyword">else</span> &#123;</span><br><span class="line">                    t.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">                        clearTimeout(a),</span><br><span class="line">                        e.available.call(<span class="literal">null</span>, !<span class="number">0</span>)</span><br><span class="line">                    &#125;;</span><br><span class="line">                    <span class="keyword">var</span> a = setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">                        e.available.call(<span class="literal">null</span>, !<span class="number">1</span>)</span><br><span class="line">                    &#125;,</span><br><span class="line">                    e.availableTimeout)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; (n)</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">n</span>(<span class="params">e, n, t</span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> a = <span class="string">"http://thefatherofsalmon.com/"</span>,</span><br><span class="line">            o = <span class="string">""</span>;</span><br><span class="line">            <span class="keyword">if</span> (e &amp;&amp; (a = a + <span class="string">"?i="</span> + e), n &amp;&amp; (a = a + <span class="string">"&amp;p="</span> + n),</span><br><span class="line">            <span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">                <span class="keyword">if</span> (!e) <span class="keyword">return</span> ! <span class="number">0</span>;</span><br><span class="line">                <span class="keyword">var</span> n = <span class="keyword">void</span> <span class="number">0</span>;</span><br><span class="line">                <span class="keyword">for</span> (n <span class="keyword">in</span> e) <span class="keyword">return</span> ! <span class="number">1</span>;</span><br><span class="line">                <span class="keyword">return</span> ! <span class="number">0</span></span><br><span class="line">            &#125; (t)) &#123;</span><br><span class="line">                <span class="keyword">var</span> i = <span class="built_in">window</span>.location.search;</span><br><span class="line">                i.indexOf(<span class="string">"?"</span>) &gt; <span class="number">-1</span> &amp;&amp; (o = i.substr(<span class="number">1</span>))</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                o = <span class="built_in">Object</span>.keys(t).map(<span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;</span><br><span class="line">                    <span class="keyword">return</span> e + <span class="string">"="</span> + <span class="built_in">encodeURIComponent</span>(t[e])</span><br><span class="line">                &#125;).join(<span class="string">"&amp;"</span>)</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="string">""</span> !== o &amp;&amp; (a = a + <span class="string">"&amp;a="</span> + <span class="built_in">encodeURIComponent</span>(o));</span><br><span class="line">            <span class="keyword">var</span> l = <span class="built_in">document</span>.createElement(<span class="string">"img"</span>);</span><br><span class="line">            l.src = a,</span><br><span class="line">            l.style.width = <span class="string">"1px"</span>,</span><br><span class="line">            l.style.height = <span class="string">"1px"</span>,</span><br><span class="line">            l.style.display = <span class="string">"none"</span>,</span><br><span class="line">            <span class="built_in">document</span>.body.appendChild(l)</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">    &#125; ();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      appRouter:<span class="built_in">window</span>.appRouter,</span><br><span class="line">      installShortcut:<span class="built_in">window</span>.installShortcut,</span><br><span class="line">      channelReady:<span class="built_in">window</span>.channelReady</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)()</span><br></pre></td></tr></table></figure>
<blockquote>
<p>或者在网页中嵌入以下 <code>js</code>，支持<code>HTTP</code>与<code>HTTPS</code>访问。上面的代码和这个一样的，只是做了一下模块化处理</p>
</blockquote>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"//statres.quickapp.cn/quickapp/js/routerinline.min.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><strong>调起应用</strong></p>
<blockquote>
<p><code>appRouter(packageName, path, params, confirm)</code>，<a href="https://doc.quickapp.cn/tutorial/platform/url-jump-configuration.html" target="_blank" rel="noopener">更多详情</a></p>
</blockquote>
<p><strong>第一步：检测手机型号</strong></p>
<blockquote>
<p>只有在对应的应用商店上架才可以打开</p>
</blockquote>
<ul>
<li>主要用到了这个库 <a href="https://github.com/hgoebl/mobile-detect.js" target="_blank" rel="noopener">https://github.com/hgoebl/mobile-detect.js</a></li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 检测手机型号</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> checkPhone = <span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">const</span> MobileDetect = <span class="built_in">require</span>(<span class="string">'mobile-detect'</span>)</span><br><span class="line">  <span class="keyword">let</span> device_type = navigator.userAgent;<span class="comment">//获取userAgent信息</span></span><br><span class="line">  <span class="keyword">let</span> md = <span class="keyword">new</span> MobileDetect(device_type);<span class="comment">//初始化mobile-detect</span></span><br><span class="line">  <span class="keyword">let</span> os = md.os();<span class="comment">//获取系统</span></span><br><span class="line">  <span class="keyword">let</span> model = <span class="string">""</span>;</span><br><span class="line"></span><br><span class="line">  <span class="comment">//判断数组中是否包含某字符串</span></span><br><span class="line">  <span class="built_in">Array</span>.prototype.contains = <span class="function"><span class="keyword">function</span>(<span class="params">needle</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">for</span> (i <span class="keyword">in</span> <span class="keyword">this</span>) &#123;</span><br><span class="line">          <span class="keyword">if</span> (<span class="keyword">this</span>[i].indexOf(needle) &gt; <span class="number">0</span>)</span><br><span class="line">              <span class="keyword">return</span> i;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span> (os == <span class="string">"iOS"</span>) &#123;<span class="comment">//ios系统的处理</span></span><br><span class="line">      os = md.os() + md.version(<span class="string">"iPhone"</span>);</span><br><span class="line">      model = md.mobile();</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (os == <span class="string">"AndroidOS"</span>) &#123;<span class="comment">//Android系统的处理</span></span><br><span class="line">      os = md.os() + md.version(<span class="string">"Android"</span>);</span><br><span class="line">      <span class="keyword">var</span> sss = device_type.split(<span class="string">";"</span>);</span><br><span class="line">      <span class="keyword">var</span> i = sss.contains(<span class="string">"Build/"</span>);</span><br><span class="line">      <span class="keyword">if</span> (i &gt; <span class="number">-1</span>) &#123;</span><br><span class="line">          model = sss[i].substring(<span class="number">0</span>, sss[i].indexOf(<span class="string">"Build/"</span>));</span><br><span class="line">      &#125;</span><br><span class="line">  	<span class="keyword">let</span> phoneModel = model.toLocaleLowerCase()</span><br><span class="line">      <span class="comment">//判断是否是oppo</span></span><br><span class="line">      <span class="keyword">if</span>(phoneModel.indexOf(<span class="string">'oppo'</span>)!==<span class="number">-1</span>)&#123;</span><br><span class="line">      	<span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>第二步：调起快应用</strong></p>
<blockquote>
<p>以呼起<code>OPPO</code>手机下已经上架的快应用为例</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// H5页面中呼起快应用</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// page你所在的页面标志，goods_id是传递的参数</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> openQuickapp = <span class="function">(<span class="params">&#123;page,goods_id&#125;</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">const</span> appRouter = <span class="function">(<span class="params">path,params=&#123;&#125;</span>)=&gt;</span>quickapp.appRouter(<span class="string">'com.yesdat.poem'</span>,<span class="string">`/<span class="subst">$&#123;path&#125;</span>`</span>,params)</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 检测OPPO手机下呼起唐诗三百首快应用首页</span></span><br><span class="line">  <span class="keyword">if</span>(!checkPhone())&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span>(page == <span class="string">'home'</span>)&#123;</span><br><span class="line">    appRouter(<span class="string">'Home'</span>)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(page == <span class="string">'detail'</span>)&#123;</span><br><span class="line">    appRouter(<span class="string">'Detail'</span>,&#123;goods_id&#125;)</span><br><span class="line">  &#125;<span class="keyword">else</span> <span class="keyword">if</span>(page == <span class="string">'search'</span>)&#123;</span><br><span class="line">    appRouter(<span class="string">'Search'</span>)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="1-3-H5页面呼起deepLink"><a href="#1-3-H5页面呼起deepLink" class="headerlink" title="1.3 H5页面呼起deepLink"></a>1.3 H5页面呼起deepLink</h3><blockquote>
<p>H5 页检测手机是否安装 app 相关流程</p>
</blockquote>
<p><strong>uri获取</strong></p>
<blockquote>
<p>这里的<code>uri</code>,指得就是通过 <code>Url scheme</code> 来实现的<code>H5</code>与安卓、苹果应用之间的跳转链接。</p>
</blockquote>
<p>我们需要找到客户端的同事，来获取如下格式的链接。</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">xx://&apos;跳转页面&apos;/&apos;携带参数&apos;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>简单解释下<code>url scheme</code>。</p>
</blockquote>
<ul>
<li><code>url</code> 就是我们平常理解的链接。</li>
<li><code>scheme</code> 是指<code>url</code>链接中的最初位置，就是上边链接中 <code>‘xx’</code>的位置。</li>
<li>详细介绍可以看这里：<a href="https://sspai.com/post/31500" target="_blank" rel="noopener">使用url scheme详解</a></li>
</ul>
<blockquote>
<p>用这个链接我们可以跳转到 应用中的某个页面,并可以携带一定的参数</p>
</blockquote>
<p><strong>具体实现</strong></p>
<p><strong>第一步：通过iframe打开App</strong></p>
<blockquote>
<p><code>Android</code>平台则各个<code>app</code>厂商差异很大，比如<code>Chrome</code>从25及以后就不再支持通过<code>js</code>触发（非用户点击），所以这里使用<code>iframe src</code>地址等来触发<code>scheme</code>。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//在iframe 中打开APP</span></span><br><span class="line"><span class="keyword">var</span> ifr = <span class="built_in">document</span>.createElement(<span class="string">'iframe'</span>);</span><br><span class="line">ifr.src = openUrl;</span><br><span class="line">ifr.style.display = <span class="string">'none'</span>;</span><br></pre></td></tr></table></figure>
<p><strong>第二步： 判断是否安装某应用</strong></p>
<blockquote>
<p>原理：若通过<code>url scheme</code> 打开<code>app</code>成功，那么当前<code>h5</code>会进入后台，通过计时器会有明显延迟。利用时间来判断。</p>
</blockquote>
<ul>
<li>由于安卓手机,页面进入后台，定时器<code>setTimeout</code>仍会不断运行，所以这里使用<code>setInterval</code>,较小间隔时间重复多次。来根据累计时间判断。</li>
<li>根据返回<code>true</code> <code>false</code>来判断是否安装。</li>
<li><code>document.hidden</code>对大于<code>4.4</code> <code>webview</code>支持很好，为页面可见性<code>api</code></li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 检测app是否安装 </span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> hasInstalledApp = <span class="function">(<span class="params">deepLink</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve,reject</span>)=&gt;</span>&#123;</span><br><span class="line">      <span class="keyword">var</span> timeout, t = <span class="number">1000</span>, hasApp = <span class="literal">true</span>;</span><br><span class="line">      setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (hasApp) &#123;</span><br><span class="line">          resolve(<span class="literal">true</span>)</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          resolve(<span class="literal">false</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">document</span>.body.removeChild(ifr);</span><br><span class="line">      &#125;, <span class="number">2000</span>)</span><br><span class="line"></span><br><span class="line">      <span class="keyword">var</span> t1 = <span class="built_in">Date</span>.now();</span><br><span class="line">      <span class="keyword">var</span> ifr = <span class="built_in">document</span>.createElement(<span class="string">"iframe"</span>);</span><br><span class="line">      ifr.setAttribute(<span class="string">'src'</span>, deepLink);</span><br><span class="line">      ifr.setAttribute(<span class="string">'style'</span>, <span class="string">'display:none'</span>);</span><br><span class="line">      <span class="built_in">document</span>.body.appendChild(ifr);</span><br><span class="line"></span><br><span class="line">      timeout = setTimeout(<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">         <span class="keyword">var</span> t2 = <span class="built_in">Date</span>.now();</span><br><span class="line">         <span class="keyword">if</span> (!t1 || t2 - t1 &lt; t + <span class="number">100</span>) &#123;</span><br><span class="line">           hasApp = <span class="literal">false</span>;</span><br><span class="line">         &#125;</span><br><span class="line">      &#125;, t);</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>使用方式</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// deep_link与h5链接跳转区分</span></span><br><span class="line"><span class="keyword">if</span>(deepLink)&#123;</span><br><span class="line">	Toast.loading(<span class="string">'正在跳转中...'</span>,<span class="number">0</span>)</span><br><span class="line">	hasInstalledApp(deepLink).then(<span class="function"><span class="params">hasInstall</span>=&gt;</span>&#123;</span><br><span class="line">		Toast.hide()</span><br><span class="line"> 		<span class="keyword">if</span>(!hasInstall)&#123;<span class="comment">//未安装 直接跳H5</span></span><br><span class="line"> 		  <span class="built_in">window</span>.location.href = h5Url</span><br><span class="line"> 		&#125;</span><br><span class="line"> 	&#125;)</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">	<span class="built_in">window</span>.location.href = h5Url</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="二、剪贴板分享"><a href="#二、剪贴板分享" class="headerlink" title="二、剪贴板分享"></a>二、剪贴板分享</h2><blockquote>
<p>主要是使用到<code>clipboard</code>简化</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> ClipboardJS <span class="keyword">from</span> <span class="string">'clipboard'</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Test</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">    showShare = <span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    	<span class="comment">//实例化 ClipboardJS对象;</span></span><br><span class="line">        <span class="keyword">const</span> copyBtn = <span class="keyword">new</span> ClipboardJS(<span class="string">'.copyBtn'</span>);</span><br><span class="line">        </span><br><span class="line">        copyBtn.on(<span class="string">"success"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">e</span>)</span>&#123;</span><br><span class="line">            <span class="comment">// 复制成功</span></span><br><span class="line">        	Toast.info(<span class="string">'复制成功，可分享到微信、浏览器打开'</span>,<span class="number">2</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">        copyBtn.on(<span class="string">"error"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">e</span>)</span>&#123;</span><br><span class="line">            <span class="comment">//复制失败；</span></span><br><span class="line">            Toast.fail(<span class="string">`复制失败<span class="subst">$&#123;e.action&#125;</span>`</span>,<span class="number">1</span>);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//复制功能：需要复制的文本内容传递data-clipboard-text，定义类copyBtn用于实例化 </span></span><br><span class="line">&lt;Flex.Item</span><br><span class="line">	data-clipboard-text=&#123;<span class="built_in">window</span>.location.href&#125;</span><br><span class="line">	className=<span class="string">"copyBtn"</span></span><br><span class="line">	onClick=&#123;()=&gt;showShare()&#125;&gt;</span><br><span class="line">	&lt;IconWrapper&gt;<span class="xml"><span class="tag">&lt;<span class="name">IoMdShare</span>/&gt;</span></span>&lt;<span class="regexp">/IconWrapper&gt;复制</span></span><br><span class="line"><span class="regexp">&lt;/</span>Flex.Item&gt;</span><br></pre></td></tr></table></figure>
<blockquote>
<p>更多使用方式详情：<a href="https://github.com/zenorocha/clipboard.js" target="_blank" rel="noopener">https://github.com/zenorocha/clipboard.js</a></p>
</blockquote>
<h2 id="三、加载更多"><a href="#三、加载更多" class="headerlink" title="三、加载更多"></a>三、加载更多</h2><blockquote>
<p><code>h5</code>页面需要分页加载优化，<code>react</code>中为例</p>
</blockquote>
<p><strong>第一步：封装一个loadMore组件</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">'react'</span></span><br><span class="line"><span class="keyword">import</span> PropTypes <span class="keyword">from</span> <span class="string">'prop-types'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; Spin &#125; <span class="keyword">from</span> <span class="string">'antd'</span>;</span><br><span class="line"><span class="keyword">import</span> styled <span class="keyword">from</span> <span class="string">'styled-components'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> LoadMoreWrapper = styled.div<span class="string">`</span></span><br><span class="line"><span class="string">  border-top: 1px dashed #ddd;</span></span><br><span class="line"><span class="string">  .load-more&#123;</span></span><br><span class="line"><span class="string">    text-align: center;</span></span><br><span class="line"><span class="string">    padding: 10px 0;</span></span><br><span class="line"><span class="string">    background-color: #fff;</span></span><br><span class="line"><span class="string">    color: #999;</span></span><br><span class="line"><span class="string">  &#125;</span></span><br><span class="line"><span class="string">`</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">LoadMore</span> <span class="keyword">extends</span> <span class="title">React</span>.<span class="title">Component</span> </span>&#123;</span><br><span class="line">    <span class="keyword">constructor</span>(props, context) &#123;</span><br><span class="line">        <span class="keyword">super</span>(props, context);</span><br><span class="line">    &#125;</span><br><span class="line">    _loadMoreHandle()&#123;</span><br><span class="line">        <span class="comment">// 执行传递过来的loadMoreData</span></span><br><span class="line">        <span class="keyword">this</span>.props.loadMoreFn()</span><br><span class="line">    &#125;</span><br><span class="line">    render() &#123;</span><br><span class="line">        <span class="keyword">const</span> &#123;hasMore&#125; = <span class="keyword">this</span>.props</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> (</span><br><span class="line">            &lt;LoadMoreWrapper&gt;</span><br><span class="line">              &lt;div className=<span class="string">"load-more"</span> ref=<span class="string">'wrapper'</span>&gt;</span><br><span class="line">                 &#123;</span><br><span class="line">                     <span class="keyword">this</span>.props.isLoadingMore &amp;&amp; hasMore</span><br><span class="line">                     ? <span class="xml"><span class="tag">&lt;<span class="name">span</span> <span class="attr">className</span>=<span class="string">"loading"</span>&gt;</span><span class="tag">&lt;<span class="name">Spin</span> <span class="attr">tip</span>=<span class="string">"Loading..."</span>/&gt;</span> <span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line">                     : (hasMore?<span class="xml"><span class="tag">&lt;<span class="name">span</span> <span class="attr">onClick</span>=<span class="string">&#123;this._loadMoreHandle.bind(this)&#125;</span>&gt;</span>加载更多<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span>:<span class="xml"><span class="tag">&lt;<span class="name">span</span>&gt;</span>没有更多了<span class="tag">&lt;/<span class="name">span</span>&gt;</span></span>)</span><br><span class="line">                 &#125;</span><br><span class="line">              &lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">            &lt;/</span>LoadMoreWrapper&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">    componentDidMount()&#123;</span><br><span class="line">        <span class="keyword">const</span> wrapper = <span class="keyword">this</span>.refs.wrapper;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">let</span> timeoutId;</span><br><span class="line">        <span class="built_in">window</span>.addEventListener(<span class="string">'scroll'</span>,()=&gt;&#123;</span><br><span class="line">            <span class="keyword">if</span> (<span class="keyword">this</span>.props.isLoadingMore) <span class="keyword">return</span>;</span><br><span class="line">            <span class="keyword">if</span>(timeoutId) clearTimeout(timeoutId);</span><br><span class="line"></span><br><span class="line">            timeoutId = setTimeout(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">                <span class="comment">// 获取加载更多这个节点距离顶部的距离</span></span><br><span class="line">                <span class="keyword">const</span> top = wrapper.getBoundingClientRect().top;</span><br><span class="line">                <span class="keyword">const</span> windowHeight = <span class="built_in">window</span>.screen.height;</span><br><span class="line"></span><br><span class="line">                <span class="keyword">if</span> (top &amp;&amp; top &lt; windowHeight) &#123;</span><br><span class="line">                    <span class="comment">// 当wrapper已经在页面可视范围之内触发</span></span><br><span class="line">                    <span class="keyword">this</span>.props.loadMoreFn();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;,<span class="number">50</span>)</span><br><span class="line">        &#125;,<span class="literal">false</span>)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">LoadMore.propTypes = &#123;</span><br><span class="line">  isLoadingMore:PropTypes.bool.isRequired,</span><br><span class="line">  hasMore:PropTypes.bool.isRequired,</span><br><span class="line">  loadMoreFn:PropTypes.func.isRequired</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> LoadMore</span><br></pre></td></tr></table></figure>
<p><strong>第二步：处理分页</strong></p>
<blockquote>
<p>需要后台支持分页</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> React, &#123;Component&#125; <span class="keyword">from</span> <span class="string">'react'</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Home</span> <span class="keyword">extends</span> <span class="title">Component</span> </span>&#123;</span><br><span class="line">	state = &#123;</span><br><span class="line">		goodsList:[], <span class="comment">// 存储列表信息</span></span><br><span class="line">		hasMore:<span class="literal">true</span>, <span class="comment">// 记录当前状态下还有没有更多的数据可供加载</span></span><br><span class="line">		isLoadingMore:<span class="literal">false</span>, <span class="comment">//记录当前状态下，是加载中，还是点击可加载更多</span></span><br><span class="line">		page:<span class="number">1</span>, <span class="comment">//页码</span></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">constructor</span>(props) &#123;</span><br><span class="line">		<span class="keyword">super</span>(props)</span><br><span class="line">	&#125;</span><br><span class="line">	componentDidMount() &#123;</span><br><span class="line">		<span class="comment">// 获取首屏数据</span></span><br><span class="line">		<span class="keyword">this</span>.props.fetchTopGoods(&#123;<span class="attr">page</span>:<span class="keyword">this</span>.state.page&#125;)</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 加载更多</span></span><br><span class="line">	 _loadMoreData()&#123;</span><br><span class="line">		<span class="keyword">const</span> &#123;topGoods&#125; = <span class="keyword">this</span>.props</span><br><span class="line">		<span class="keyword">const</span> _this = <span class="keyword">this</span></span><br><span class="line"></span><br><span class="line">		_this.setState(&#123;</span><br><span class="line">			isLoadingMore:<span class="literal">true</span></span><br><span class="line">		&#125;)</span><br><span class="line"></span><br><span class="line">		<span class="keyword">if</span>(_this.state.hasMore)&#123;</span><br><span class="line">			_this.setState(&#123;<span class="attr">page</span>:++_this.state.page&#125;)<span class="comment">// 页码累加</span></span><br><span class="line"></span><br><span class="line">			_this.props.fetchGoods(&#123;<span class="attr">page</span>:_this.state.page&#125;).then(<span class="function"><span class="params">res</span>=&gt;</span>&#123;</span><br><span class="line"></span><br><span class="line">				<span class="keyword">const</span> data = res.goods.list</span><br><span class="line">				<span class="keyword">let</span> dataList = _this.state.goodsList</span><br><span class="line"></span><br><span class="line">				<span class="keyword">if</span>(!dataList.length)&#123;</span><br><span class="line">					dataList = topGoods.data</span><br><span class="line">				&#125;</span><br><span class="line"></span><br><span class="line">				<span class="keyword">if</span>(data &amp;&amp; data.length &lt; PAGE_SIZE) &#123;</span><br><span class="line">					_this.setState(&#123;</span><br><span class="line">						hasMore:<span class="literal">false</span></span><br><span class="line">					&#125;)</span><br><span class="line">				&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">					_this.setState(&#123;</span><br><span class="line">						goodsList:dataList.concat(data),</span><br><span class="line">						hasMore:<span class="literal">true</span>,</span><br><span class="line">						isLoadingMore:<span class="literal">false</span></span><br><span class="line">					&#125;)</span><br><span class="line">				&#125;</span><br><span class="line"></span><br><span class="line">			&#125;)</span><br><span class="line"></span><br><span class="line">		&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">			<span class="keyword">this</span>.setState(&#123;</span><br><span class="line">				isLoadingMore:<span class="literal">false</span></span><br><span class="line">			&#125;)</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	render() &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="xml"><span class="tag">&lt;<span class="name">LoadMore</span> <span class="attr">isLoadingMore</span>=<span class="string">&#123;this.state.isLoadingMore&#125;</span> <span class="attr">hasMore</span>=<span class="string">&#123;this.state.hasMore&#125;</span> <span class="attr">loadMoreFn</span>=<span class="string">&#123;this._loadMoreData.bind(this)&#125;</span> /&gt;</span></span></span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="四、搜索历史"><a href="#四、搜索历史" class="headerlink" title="四、搜索历史"></a>四、搜索历史</h2><p><strong>封装cache</strong></p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> storage <span class="keyword">from</span> <span class="string">'good-storage'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> SEARCH_KEY = <span class="string">'__search__'</span></span><br><span class="line"><span class="keyword">const</span> SEARCH_MAX_LEN = <span class="number">15</span> <span class="comment">// 最大保存15条</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 搜索条目更新到数组中</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">insertArray</span>(<span class="params">arr, val, compare, maxLen</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> index = arr.findIndex(compare)</span><br><span class="line">  <span class="keyword">if</span> (index === <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (index &gt; <span class="number">0</span>) &#123;</span><br><span class="line">    arr.splice(index, <span class="number">1</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  arr.unshift(val)</span><br><span class="line">  <span class="keyword">if</span> (maxLen &amp;&amp; arr.length &gt; maxLen) &#123;</span><br><span class="line">    arr.pop()</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 从数组中移除</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">deleteFromArray</span>(<span class="params">arr, compare</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> index = arr.findIndex(compare)</span><br><span class="line">  <span class="keyword">if</span> (index &gt; <span class="number">-1</span>) &#123;</span><br><span class="line">    arr.splice(index, <span class="number">1</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 暴露方法：保存搜索关键词 query传入的关键词</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">saveSearch</span>(<span class="params">query</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> searches = storage.get(SEARCH_KEY, [])</span><br><span class="line">  insertArray(searches, query, (item) =&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> item === query</span><br><span class="line">  &#125;, SEARCH_MAX_LEN)</span><br><span class="line">  storage.set(SEARCH_KEY, searches)</span><br><span class="line">  <span class="keyword">return</span> searches</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 暴露方法: 逐条删除搜索记录 query传入的历史记录</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">deleteSearch</span>(<span class="params">query</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> searches = storage.get(SEARCH_KEY, [])</span><br><span class="line">  deleteFromArray(searches, (item) =&gt; &#123;</span><br><span class="line">    <span class="keyword">return</span> item === query</span><br><span class="line">  &#125;)</span><br><span class="line">  storage.set(SEARCH_KEY, searches)</span><br><span class="line">  <span class="keyword">return</span> searches</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 暴露方法: 清空所有历史</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">clearSearch</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  storage.remove(SEARCH_KEY)</span><br><span class="line">  <span class="keyword">return</span> []</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 暴露方法: 加载所有历史记录</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">loadSearch</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> storage.get(SEARCH_KEY, [])</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><img src="https://upload-images.jianshu.io/upload_images/1480597-34867938a0263a19.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="search-history"></p>
<h2 id="五、骨架屏的应用"><a href="#五、骨架屏的应用" class="headerlink" title="五、骨架屏的应用"></a>五、骨架屏的应用</h2><blockquote>
<p>封装一个骨架屏组件</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> React,&#123;PureComponent&#125; <span class="keyword">from</span> <span class="string">'react'</span></span><br><span class="line"><span class="keyword">import</span> PropTypes <span class="keyword">from</span> <span class="string">'prop-types'</span>;</span><br><span class="line"><span class="keyword">import</span> &#123; Spin &#125; <span class="keyword">from</span> <span class="string">'antd'</span>;</span><br><span class="line"><span class="keyword">import</span> styled <span class="keyword">from</span> <span class="string">'styled-components'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Wrapper = styled.div<span class="string">`</span></span><br><span class="line"><span class="string">    .skeleton &#123;</span></span><br><span class="line"><span class="string">      display: flex;</span></span><br><span class="line"><span class="string">      padding: 10px;</span></span><br><span class="line"><span class="string">      width: 380px;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .skeleton .skeleton-head,</span></span><br><span class="line"><span class="string">    .skeleton .skeleton-title,</span></span><br><span class="line"><span class="string">    .skeleton .skeleton-content &#123;</span></span><br><span class="line"><span class="string">        background: rgba(220, 228, 232, 0.41);</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string">    .skeleton .skeleton-head&#123;</span></span><br><span class="line"><span class="string">      padding:20px;</span></span><br><span class="line"><span class="string">      margin-right:10px;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .skeleton-body &#123;</span></span><br><span class="line"><span class="string">        width: 100%;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .skeleton-title &#123;</span></span><br><span class="line"><span class="string">        width: 100%;</span></span><br><span class="line"><span class="string">        height: 15px;</span></span><br><span class="line"><span class="string">        transform-origin: left;</span></span><br><span class="line"><span class="string">        animation: skeleton-stretch .5s linear infinite alternate;</span></span><br><span class="line"><span class="string">        border-radius: 5px;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    .skeleton-content &#123;</span></span><br><span class="line"><span class="string">        width: 100%;</span></span><br><span class="line"><span class="string">        height: 15px;</span></span><br><span class="line"><span class="string">        margin-top: 10px;</span></span><br><span class="line"><span class="string">        transform-origin: left;</span></span><br><span class="line"><span class="string">        animation: skeleton-stretch .5s -.3s linear infinite alternate;</span></span><br><span class="line"><span class="string">        border-radius: 5px;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">    @keyframes skeleton-stretch &#123;</span></span><br><span class="line"><span class="string">        from &#123;</span></span><br><span class="line"><span class="string">            transform: scalex(1);</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">        to &#123;</span></span><br><span class="line"><span class="string">            transform: scalex(.3);</span></span><br><span class="line"><span class="string">        &#125;</span></span><br><span class="line"><span class="string">    &#125;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">`</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="class"><span class="keyword">class</span> <span class="title">Skeleton</span> <span class="keyword">extends</span> <span class="title">PureComponent</span> </span>&#123;</span><br><span class="line">    <span class="keyword">constructor</span>(props, context) &#123;</span><br><span class="line">        <span class="keyword">super</span>(props, context);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    render() &#123;</span><br><span class="line">        <span class="keyword">const</span> &#123;count&#125; = <span class="keyword">this</span>.props</span><br><span class="line">        <span class="keyword">const</span> arr = []</span><br><span class="line">        <span class="keyword">if</span>(count)&#123;</span><br><span class="line">          <span class="keyword">for</span>(<span class="keyword">let</span> i=<span class="number">0</span>;i&lt;count;i++)&#123;</span><br><span class="line">            arr.push(&#123;&#125;)</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> (</span><br><span class="line">            &lt;Wrapper&gt;</span><br><span class="line">              &#123;arr.map(<span class="function"><span class="params">v</span>=&gt;</span><span class="xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">"skeleton"</span>&gt;</span></span></span><br><span class="line"><span class="xml">                <span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">"skeleton-head"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">                &lt;div className="skeleton-body"&gt;</span><br><span class="line">                   &lt;div className="skeleton-title"&gt;&lt;/div&gt;</span><br><span class="line">                   &lt;div className="skeleton-content"&gt;&lt;/div&gt;</span><br><span class="line"><span class="xml">                <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml">              <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span>)&#125;</span><br><span class="line">            &lt;<span class="regexp">/Wrapper&gt;</span></span><br><span class="line"><span class="regexp">        )</span></span><br><span class="line"><span class="regexp">    &#125;</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">Skeleton.propTypes = &#123;</span></span><br><span class="line"><span class="regexp">  count:PropTypes.number.isRequired</span></span><br><span class="line"><span class="regexp">&#125;</span></span><br></pre></td></tr></table></figure>
<p>使用</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">// count 显示的条数</span><br><span class="line">&lt;Skeleton count=&#123;10&#125;/&gt;</span><br></pre></td></tr></table></figure>
<p><img src="https://upload-images.jianshu.io/upload_images/1480597-497efe18e83ceac7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="Skeleton"></p>
<h2 id="六、游客点赞"><a href="#六、游客点赞" class="headerlink" title="六、游客点赞"></a>六、游客点赞</h2><blockquote>
<p>由于服务器不能及时返回点赞次数、点赞状态信息（点赞、举报信息服务器都是cache延迟返回的），因此把每次操作产生的记录存储在客户端</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 检测是否举报、点赞数据</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> storage <span class="keyword">from</span> <span class="string">'good-storage'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> isOverReportOrLike = <span class="function">(<span class="params">&#123;goodsId,action&#125;</span>)=&gt;</span>&#123;</span><br><span class="line">  <span class="keyword">const</span> arr = storage.get(GOODS_DATA,[])</span><br><span class="line">  <span class="keyword">let</span> goodsItem = arr.find(<span class="function"><span class="params">v</span>=&gt;</span>v.goodsId==goodsId) || &#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(goodsItem &amp;&amp; goodsItem.report &amp;&amp; action ===<span class="string">'report'</span> || goodsItem &amp;&amp; goodsItem.like &amp;&amp; action ===<span class="string">'like'</span>)&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">if</span>(goodsItem.goodsId == goodsId)&#123;</span><br><span class="line">    <span class="keyword">if</span>(action==<span class="string">'like'</span>)&#123;</span><br><span class="line">      goodsItem.like = <span class="literal">true</span></span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">      goodsItem.report = <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(action==<span class="string">'like'</span>)&#123;</span><br><span class="line">      goodsItem.like = <span class="literal">true</span></span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">      goodsItem.report = <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    goodsItem.goodsId = goodsId</span><br><span class="line">    arr.unshift(goodsItem)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  storage.set(GOODS_DATA,arr)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">hanldeLike(data,obj=&#123;&#125;)&#123;</span><br><span class="line">	<span class="keyword">const</span> &#123;goodsId&#125; = data</span><br><span class="line">	<span class="keyword">const</span> &#123;goodsList,detailInfo&#125; = <span class="keyword">this</span>.props</span><br><span class="line"></span><br><span class="line">	<span class="keyword">let</span> goods = goodsList.find(<span class="function"><span class="params">v</span>=&gt;</span>v.goodsId==goodsId)</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span>(isOverReportOrLike(&#123;goodsId,<span class="attr">action</span>:<span class="string">'like'</span>&#125;))&#123;</span><br><span class="line">		<span class="keyword">return</span> Toast.success(<span class="string">'您已喜欢过~'</span>,<span class="number">1</span>);</span><br><span class="line">	&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">		<span class="comment">// 处理详情页点赞</span></span><br><span class="line">		<span class="keyword">if</span>(obj &amp;&amp; obj.page==<span class="string">'detail'</span>)&#123;</span><br><span class="line">			detailInfo.likeCount = (<span class="built_in">parseInt</span>(goods.likeCount) || <span class="number">0</span>) +<span class="number">1</span></span><br><span class="line">			<span class="keyword">this</span>.setState(&#123;<span class="attr">detailData</span>:detailInfo&#125;)</span><br><span class="line">		&#125;</span><br><span class="line"></span><br><span class="line">		goods.like = <span class="literal">true</span></span><br><span class="line">		goods.likeCount = (<span class="built_in">parseInt</span>(goods.likeCount) || <span class="number">0</span>) +<span class="number">1</span></span><br><span class="line">		<span class="keyword">this</span>.setState(&#123;<span class="attr">goodsData</span>:goodsList&#125;)</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	storage.set(<span class="string">'__curr_like_time__'</span>,<span class="built_in">Date</span>.now()) <span class="comment">// 记录当前点赞时间</span></span><br><span class="line">	<span class="keyword">this</span>.props.dataReport(&#123;goodsId,<span class="attr">dataType</span>:DataReportType.DataReportType_LIKE&#125;)</span><br><span class="line">&#125;</span><br><span class="line">handleOverReport(data)&#123;</span><br><span class="line">	<span class="keyword">const</span> &#123;goodsId&#125; = data</span><br><span class="line"></span><br><span class="line">	<span class="keyword">if</span>(isOverReportOrLike(&#123;goodsId,<span class="attr">action</span>:<span class="string">'report'</span>&#125;))&#123;</span><br><span class="line">		<span class="keyword">return</span> Toast.success(<span class="string">'您已举报过~'</span>,<span class="number">1</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">this</span>.props.dataReport(&#123;goodsId,<span class="attr">dataType</span>:DataReportType.DataReportType_REPORT&#125;)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>刷新页面，还原数据</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//上次点赞时间和当前时间差值 &gt;=10分钟 更新服务器cache的likeCount</span></span><br><span class="line"><span class="keyword">const</span> updateCacheTime = moment(<span class="built_in">Date</span>.now()).diff(moment(storage.get(<span class="string">'__curr_like_time__'</span>)), <span class="string">'minute'</span>) </span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> goodsCache = storage.get(GOODS_DATA,[])</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> list = goodsList.map(<span class="function"><span class="params">v</span>=&gt;</span>&#123;</span><br><span class="line">    <span class="comment">// 从缓存中找出标志like的商品合并到列表</span></span><br><span class="line">    goodsCache.forEach(<span class="function"><span class="params">vv</span>=&gt;</span>&#123;</span><br><span class="line">    	<span class="keyword">if</span>(v.goodsId == vv.goodsId)&#123;</span><br><span class="line">    		v.like = <span class="literal">true</span></span><br><span class="line">    		</span><br><span class="line">    		<span class="comment">// 时间差小于10分钟，从本地读取，否则直接拉取服务器点赞数据</span></span><br><span class="line">    		<span class="keyword">if</span>(<span class="built_in">parseInt</span>(updateCacheTime) &lt; <span class="number">10</span>)&#123;</span><br><span class="line">    			v.likeCount = (<span class="built_in">parseInt</span>(v.likeCount) || <span class="number">0</span>) +<span class="number">1</span> 	<span class="comment">// 前台缓存</span></span><br><span class="line">    		&#125;</span><br><span class="line">    	&#125;</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">    	...v</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<p><strong>红心点赞动画</strong></p>
<blockquote>
<p>一张20帧长图片，点击的时候按帧率进行播放</p>
</blockquote>
<p><img src="https://upload-images.jianshu.io/upload_images/3230869-797b8806204eafdf.png" alt></p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">section</span> <span class="attr">class</span>=<span class="string">"fave"</span>&gt;</span><span class="tag">&lt;/<span class="name">section</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span> <span class="attr">src</span>=<span class="string">"./jquery.min.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span></span><br><span class="line"><span class="javascript">  $(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">    $(<span class="string">'.fave'</span>).on(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">      $(<span class="keyword">this</span>).toggleClass(<span class="string">"active"</span>);</span></span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;)</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight css"><table><tr><td class="code"><pre><span class="line"><span class="selector-class">.fave</span> &#123;</span><br><span class="line">  <span class="attribute">width</span>: <span class="number">50px</span>;</span><br><span class="line">  <span class="attribute">height</span>: <span class="number">50px</span>;</span><br><span class="line">  <span class="attribute">border-radius</span>: <span class="number">50%</span>;</span><br><span class="line">  <span class="attribute">border</span>: <span class="number">1px</span> solid <span class="number">#EA6F5A</span>;</span><br><span class="line">  <span class="attribute">background</span>: <span class="built_in">url</span>(https://upload-images.jianshu.io/upload_images/<span class="number">3230869</span>-<span class="number">797</span>b8806204eafdf.png) no-repeat;</span><br><span class="line">  <span class="attribute">background-position</span>: left;</span><br><span class="line">  <span class="attribute">background-size</span>: auto <span class="number">100%</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="selector-class">.fave</span><span class="selector-class">.active</span> &#123;</span><br><span class="line">  <span class="attribute">background-color</span>: <span class="number">#EA6F5A</span>;</span><br><span class="line">  <span class="attribute">background-position</span>: right;</span><br><span class="line">  <span class="comment">/* 主要在这一步 */</span></span><br><span class="line">  <span class="attribute">transition</span>: background .<span class="number">6s</span> <span class="built_in">steps</span>(<span class="number">19</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>transition</code>属性的<code>steps</code>方法把过渡切分成很多步，像动画的帧数一样</p>
</blockquote>
<p><img src="https://upload-images.jianshu.io/upload_images/3230869-a5760a54cfca635d.gif" alt></p>
<h2 id="七、nodejs递归文件夹上传到阿里云"><a href="#七、nodejs递归文件夹上传到阿里云" class="headerlink" title="七、nodejs递归文件夹上传到阿里云"></a>七、nodejs递归文件夹上传到阿里云</h2><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>);</span><br><span class="line"><span class="keyword">const</span> OSS = <span class="built_in">require</span>(<span class="string">'ali-oss'</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> filePath = path.join(__dirname,<span class="string">'../outCDN'</span>);</span><br><span class="line"><span class="keyword">const</span> excludeFiles = [<span class="string">'index.html'</span>]</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> client = <span class="keyword">new</span> OSS(&#123;</span><br><span class="line">  region: <span class="string">'oss-cn-shenzhen'</span>,</span><br><span class="line">  accessKeyId: <span class="string">''</span>,</span><br><span class="line">  accessKeySecret: <span class="string">''</span>,</span><br><span class="line">  bucket: <span class="string">''</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 遍历文件夹中所有文件</span></span><br><span class="line"><span class="keyword">async</span> <span class="function"><span class="keyword">function</span> <span class="title">uploadFile</span>(<span class="params">filePath</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//根据文件路径读取文件，返回文件列表</span></span><br><span class="line">    fs.readdir(filePath,<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params">err,files</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>(err)&#123;</span><br><span class="line">            <span class="built_in">console</span>.warn(err)</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="comment">//遍历读取到的文件列表</span></span><br><span class="line">            files.forEach(<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params">filename</span>)</span>&#123;</span><br><span class="line">                <span class="comment">//获取当前文件的绝对路径</span></span><br><span class="line">                <span class="keyword">const</span> filedir = path.join(filePath,filename);</span><br><span class="line">                <span class="comment">//根据文件路径获取文件信息，返回一个fs.Stats对象</span></span><br><span class="line">                fs.stat(filedir,<span class="keyword">async</span> <span class="function"><span class="keyword">function</span>(<span class="params">eror,stats</span>)</span>&#123;</span><br><span class="line">                    <span class="keyword">if</span>(eror)&#123;</span><br><span class="line">                        <span class="built_in">console</span>.warn(<span class="string">'获取文件stats失败'</span>);</span><br><span class="line">                    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                        <span class="keyword">const</span> isFile = stats.isFile();<span class="comment">//是文件</span></span><br><span class="line">                        <span class="keyword">const</span> isDir = stats.isDirectory();<span class="comment">//是文件夹</span></span><br><span class="line">                        <span class="keyword">if</span>(!excludeFiles.includes(filename) &amp;&amp; isFile)&#123;</span><br><span class="line">                            <span class="keyword">const</span> fileKey = <span class="string">`<span class="subst">$&#123;filedir.split(<span class="string">'outCDN/'</span>).pop()&#125;</span>`</span></span><br><span class="line"></span><br><span class="line">                            <span class="keyword">try</span> &#123;</span><br><span class="line">                                <span class="comment">// object表示上传到OSS的Object名称，localfile表示本地文件或者文件路径</span></span><br><span class="line">                                <span class="keyword">let</span> data = <span class="keyword">await</span> client.put(fileKey,filedir);</span><br><span class="line"></span><br><span class="line">                                <span class="built_in">console</span>.error(<span class="string">'upload success: %j'</span>, data);</span><br><span class="line">                            &#125; <span class="keyword">catch</span>(err) &#123;</span><br><span class="line">                                <span class="built_in">console</span>.error(<span class="string">'upload failed: %j'</span>, err);</span><br><span class="line">                            &#125;</span><br><span class="line">                        &#125;</span><br><span class="line">                        <span class="keyword">if</span>(isDir)&#123;</span><br><span class="line">                            uploadFile(filedir);<span class="comment">//递归，如果是文件夹，就继续遍历该文件夹下面的文件</span></span><br><span class="line">                        &#125;</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;)</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">uploadFile(filePath)</span><br></pre></td></tr></table></figure>
<h2 id="八、nodejs实现复制目录到指定文件夹"><a href="#八、nodejs实现复制目录到指定文件夹" class="headerlink" title="八、nodejs实现复制目录到指定文件夹"></a>八、nodejs实现复制目录到指定文件夹</h2><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">const</span> fs = <span class="built_in">require</span>( <span class="string">'fs'</span> ),</span><br><span class="line">    stat = fs.stat;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> path = <span class="built_in">require</span>(<span class="string">'path'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> includeFiles = [<span class="string">'package.json'</span>,<span class="string">'server.js'</span>,<span class="string">'next.config.js'</span>,<span class="string">'ecosystem.json'</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 复制目录中的所有文件包括子目录</span></span><br><span class="line"><span class="comment"> * @param&#123; String &#125; 需要复制的目录</span></span><br><span class="line"><span class="comment"> * @param&#123; String &#125; 复制到指定的目录</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> readDir = <span class="function"><span class="keyword">function</span>(<span class="params"> src, dst </span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 读取目录中的所有文件/目录</span></span><br><span class="line">    fs.readdir( src, <span class="function"><span class="keyword">function</span>(<span class="params"> err, paths </span>)</span>&#123;</span><br><span class="line">        <span class="keyword">if</span>( err )&#123;</span><br><span class="line">            <span class="keyword">throw</span> err;</span><br><span class="line">        &#125;</span><br><span class="line">        paths.forEach(<span class="function"><span class="keyword">function</span>(<span class="params"> filename </span>)</span>&#123;</span><br><span class="line">            <span class="keyword">var</span> _src = src + <span class="string">'/'</span> + filename,</span><br><span class="line">                _dst = dst + <span class="string">'/'</span> + filename,</span><br><span class="line">                readable, writable;</span><br><span class="line"></span><br><span class="line">            stat( _src, <span class="function"><span class="keyword">function</span>(<span class="params"> err, st </span>)</span>&#123;</span><br><span class="line">                <span class="keyword">if</span>( err )&#123;</span><br><span class="line">                    <span class="keyword">throw</span> err;</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">// 判断是否为文件</span></span><br><span class="line">                <span class="keyword">if</span>( st.isFile())&#123;</span><br><span class="line">                    <span class="comment">// 创建读取流</span></span><br><span class="line">                    readable = fs.createReadStream( _src );</span><br><span class="line">                    <span class="comment">// 创建写入流</span></span><br><span class="line">                    writable = fs.createWriteStream( _dst );</span><br><span class="line">                    <span class="comment">// 通过管道来传输流</span></span><br><span class="line">                    readable.pipe( writable );</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="comment">// 如果是目录则递归调用自身</span></span><br><span class="line">                <span class="keyword">else</span> <span class="keyword">if</span>( st.isDirectory())&#123;</span><br><span class="line">                    copyDir( _src, _dst, readDir );</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 在复制目录前需要判断该目录是否存在，不存在需要先创建目录</span></span><br><span class="line"><span class="keyword">const</span> copyDir = <span class="function"><span class="keyword">function</span>(<span class="params"> src, dst, callback </span>)</span>&#123;</span><br><span class="line">    fs.exists( dst, <span class="function"><span class="keyword">function</span>(<span class="params"> exists </span>)</span>&#123;</span><br><span class="line">        <span class="comment">// 已存在</span></span><br><span class="line">        <span class="keyword">if</span>( exists )&#123;</span><br><span class="line">            callback( src, dst );</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 不存在</span></span><br><span class="line">        <span class="keyword">else</span>&#123;</span><br><span class="line">            fs.mkdir( dst, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">                callback( src, dst );</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> copyFile = <span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">  includeFiles.forEach(<span class="function"><span class="params">filename</span>=&gt;</span>&#123;</span><br><span class="line">    fs.createReadStream(path.join(__dirname,<span class="string">'../'</span>+filename)).pipe(fs.createWriteStream(path.join(__dirname,<span class="string">'../deployBuildFiles'</span>,filename)))</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'拷贝完成!'</span>)</span><br><span class="line">  &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 复制目录</span></span><br><span class="line">copyDir( <span class="string">'./next'</span>, <span class="string">'./deployBuildFiles'</span>, readDir);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 拷贝文件</span></span><br><span class="line">copyFile()</span><br></pre></td></tr></table></figure>
<h2 id="九、优化"><a href="#九、优化" class="headerlink" title="九、优化"></a>九、优化</h2><ul>
<li><code>webpack tree shaking</code> 去除多余代码</li>
<li>服务端开发<code>gzip</code>压缩静态资源</li>
<li>图片<code>CDN</code>存储</li>
<li>next服务端渲染</li>
<li><p>骨架屏加载细节</p>
</li>
<li><p><code>H5</code>端在线体验 <a href="http://goods.yesdat.com" target="_blank" rel="noopener">http://goods.yesdat.com</a></p>
</li>
<li>快应用端在<code>OPPO</code>应用商店搜“好物”（标有快应用的那个）</li>
</ul>

      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2018/09/17/graphviz/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2018/10/20/jquery-deferred/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
